"use client";

import React, { useState, useEffect } from 'react';
import { Table, Card, Button, Modal, message, Tag, Space } from 'antd';
import dayjs from 'dayjs';
import { getRecruitmentAnnouncements, PlanType, ApproveStatus, deleteRecruitmentAnnouncement } from '@/lib/recruitment';
import dynamic from 'next/dynamic';
import Layout from '@/components/Layout';
import { fetchEmployeeData } from '@/lib/user';
import { useRouter } from 'next/navigation';

// 定义组件Props类型
interface DeptManageFormProps {
	selectedPlanId: string;
	onCancel: () => void;
	onSuccess: () => void;
}

interface AttachmentManagePageProps {
	planId: string;
	onCancel: () => void;
}

interface EditPlanFormProps {
	planId: string;
}

interface CreatePlanFormProps {
	onCancel: () => void;
	onSuccess: () => void;
}

// 动态导入组件
const EditPlanForm = dynamic<EditPlanFormProps>(
	() => import('./edit/page'), 
	{ ssr: false }
);

const AttachmentManagePage = dynamic<AttachmentManagePageProps>(
	() => import('./attachment/page'), 
	{ ssr: false }
);

// 用人部门管理组件 - 使用明确的类型
const DeptManageFormComponent = dynamic<DeptManageFormProps>(
	() => import('./dept-manage/component'),
	{ ssr: false }
);

// 创建计划组件
const CreatePlanFormDynamic = dynamic<CreatePlanFormProps>(
	() => import('./create/page'), 
	{ ssr: false }
);

const RecruitmentManagementPage: React.FC = () => {
	const router = useRouter();
	const [formVisible, setFormVisible] = useState(false);
	const [editModalVisible, setEditModalVisible] = useState(false);
	const [attachmentModalVisible, setAttachmentModalVisible] = useState(false);
	const [deptManageModalVisible, setDeptManageModalVisible] = useState(false);
	const [selectedPlanId, setSelectedPlanId] = useState<string | null>(null);
	const [loading, setLoading] = useState(false);
	const [data, setData] = useState<any[]>([]);
	const [employeeOptions, setEmployeeOptions] = useState<any[]>([]);
	const [createModalVisible, setCreateModalVisible] = useState(false);

	console.log("当前createModalVisible状态:", createModalVisible);

	// 获取招聘计划列表
	const loadData = async () => {
		console.log("开始加载数据");
		setLoading(true);
		try {
			const response = await getRecruitmentAnnouncements();
			console.log("获取招聘计划结果:", response);
			if (response && response.code === 1) {
				setData(response.data);
				console.log("数据已更新:", response.data);
			} else {
				message.error(response?.msg || '获取招聘计划失败');
			}
		} catch (error: any) {
			console.error("加载数据失败:", error);
			message.error('加载数据失败');
		} finally {
			setLoading(false);
		}
	};

	// 获取所有员工作为选项
	const fetchEmployees = async () => {
		try {
			const response = await fetchEmployeeData({ page: 1, pageSize: 100 });
			if (response.data && response.data.code === 1) {
				// 确保我们使用正确的数据结构
				const employees = response.data.data.row || [];
				setEmployeeOptions(
					employees.map((emp: any) => ({
						value: emp.employeeId,
						label: `${emp.username} (${emp.employeeId})`,
						department: emp.deptName
					}))
				);
			} else {
				message.error('获取员工列表失败');
			}
		} catch (error) {
			console.error('获取员工列表失败:', error);
			message.error('获取员工列表失败');
		}
	};

	useEffect(() => {
		loadData();
		fetchEmployees(); // 组件加载时获取员工列表
	}, []);

	const handleEdit = (planId: number) => {
		setSelectedPlanId(planId.toString());
		setEditModalVisible(true);
	};

	const handleDeptManage = (planId: number) => {
		setSelectedPlanId(planId.toString());
		setDeptManageModalVisible(true);
	};

	// 添加删除处理函数
	const handleDelete = (planId: number) => {
		Modal.confirm({
			title: '确认删除',
			content: '确定要删除这条招聘公告吗？删除后不可恢复。',
			okText: '确认',
			cancelText: '取消',
			onOk: async () => {
				try {
					await deleteRecruitmentAnnouncement(planId);
					message.success('删除成功');
					loadData(); // 重新加载数据
				} catch (error: any) {
					message.error(error.message || '删除失败');
				}
			}
		});
	};

	// 关闭附件管理模态框
	const handleCloseAttachment = () => {
		setAttachmentModalVisible(false);
	};

	// 打开附件管理模态框
	const handleOpenAttachment = (planId: number) => {
		setSelectedPlanId(planId.toString());
		setAttachmentModalVisible(true);
	};

	// 当附件管理模态框关闭时，清除URL参数的useEffect
	useEffect(() => {
		if (!attachmentModalVisible) {
			// 避免影响其他使用URL参数的组件
			const currentParams = new URLSearchParams(window.location.search);
			if (currentParams.has('planId')) {
				window.history.pushState({}, '', window.location.pathname);
			}
		}
	}, [attachmentModalVisible]);

	const getPlanTypeTag = (type: number) => {
		switch (type) {
			case PlanType.MANAGEMENT:
				return <Tag color="blue">管理岗位</Tag>;
			case PlanType.TEACHER:
				return <Tag color="green">专任教师</Tag>;
			case PlanType.OTHER:
				return <Tag color="orange">其他岗位</Tag>;
			default:
				return <Tag>未知类型</Tag>;
		}
	};

	const getStatusTag = (status: number) => {
		switch (status) {
			case ApproveStatus.PENDING_PUBLISH:
				return <Tag color="warning">发布未审批</Tag>;
			case ApproveStatus.PENDING_MODIFY:
				return <Tag color="processing">修改未审批</Tag>;
			case ApproveStatus.APPROVED:
				return <Tag color="success">已通过</Tag>;
			case ApproveStatus.REJECTED:
				return <Tag color="error">已拒绝</Tag>;
			default:
				return <Tag>未知状态</Tag>;
		}
	};

	const renderOperations = (record: any) => {
		return (
			<Space>
				<Button
					size="small"
					type="primary"
					onClick={() => handleEdit(record.planId)}
				>
					查看基本信息
				</Button>
				{/* 只有管理岗位和专任教师招聘才显示用人部门管理按钮 */}
				{(record.planType === 1 || record.planType === 2) && (
					<Button
						size="small"
						type="default"
						onClick={() => handleDeptManage(record.planId)}
					>
						用人部门管理
					</Button>
				)}
				<Button
					size="small"
					type="default"
					onClick={() => handleOpenAttachment(record.planId)}
				>
					附件管理
				</Button>
				<Button
					size="small"
					danger
					onClick={() => handleDelete(record.planId)}
				>
					删除
				</Button>
			</Space>
		);
	};

	const columns = [
		{
			title: '计划编号',
			dataIndex: 'planCode',
			key: 'planCode',
		},
		{
			title: '计划名称',
			dataIndex: 'planName',
			key: 'planName',
		},
		{
			title: '计划类型',
			dataIndex: 'planType',
			key: 'planType',
			render: (type: number) => getPlanTypeTag(type),
		},
		{
			title: '发布日期',
			dataIndex: 'publishDate',
			key: 'publishDate',
			render: (date: string) => (date ? dayjs(date).format('YYYY-MM-DD') : ''),
		},
		{
			title: '开始日期',
			dataIndex: 'startDate',
			key: 'startDate',
			render: (date: string) => (date ? dayjs(date).format('YYYY-MM-DD') : ''),
		},
		{
			title: '结束日期',
			dataIndex: 'endDate',
			key: 'endDate',
			render: (date: string) => (date ? dayjs(date).format('YYYY-MM-DD') : ''),
		},
		{
			title: '审批状态',
			dataIndex: 'approveStatus',
			key: 'approveStatus',
			render: (status: number) => getStatusTag(status),
		},
		{
			title: '审批人工号',
			dataIndex: 'approverId',
			key: 'approverId',
			render: (approverId: string) => approverId ? approverId : '暂未审批',
		},
		{
			title: '创建人姓名',
			dataIndex: 'createdBy',
			key: 'createdBy',
		},
		{
			title: '创建时间',
			dataIndex: 'createdAt',
			key: 'createdAt',
			render: (date: string) => (date ? dayjs(date).format('YYYY-MM-DD') : ''),
		},
		{
			title: '更新人姓名',
			dataIndex: 'updatedBy',
			key: 'updatedBy',
		},
		{
			title: '更新时间',
			dataIndex: 'updatedAt',
			key: 'updatedAt',
			render: (date: string) => (date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : ''),
		},
		{
			title: '操作',
			key: 'action',
			render: (_, record) => renderOperations(record)
		},
	];

	// 处理模态框关闭
	const handleModalClose = () => {
		console.log("关闭创建计划模态框");
		setCreateModalVisible(false);
	};

	// 处理创建成功
	const handleCreateSuccess = () => {
		console.log("创建计划成功，关闭模态框并刷新数据");
		setCreateModalVisible(false);
		loadData();
	};

	return (
		<Layout>
			<Card title="招聘计划管理">
				<Space style={{ marginBottom: 16 }}>
					<Button type="primary" onClick={() => setCreateModalVisible(true)}>
						新建招聘计划
					</Button>
					<Button onClick={() => loadData()}>
						刷新数据
					</Button>
				</Space>
				<Table columns={columns} dataSource={data} loading={loading} rowKey="planId" />
				
				{/* 创建计划模态框 */}
				<Modal
					title="创建招聘计划"
					open={createModalVisible}
					onCancel={handleModalClose}
					footer={null}
					width={800}
					maskClosable={false}
					destroyOnClose={true}
				>
					{createModalVisible && (
						<CreatePlanFormDynamic 
							onCancel={handleModalClose}
							onSuccess={handleCreateSuccess}
						/>
					)}
				</Modal>
				
				{/* 编辑计划模态框 */}
				<Modal
					title="编辑招聘计划"
					open={editModalVisible}
					onCancel={() => setEditModalVisible(false)}
					footer={null}
					width={800}
					destroyOnClose={true}
					getContainer={false}
					bodyStyle={{ maxHeight: '70vh', overflow: 'auto' }}
				>
					{editModalVisible && <EditPlanForm planId={selectedPlanId || ''} />}
				</Modal>

				{/* 用人部门管理模态框 */}
				<Modal
					title="用人部门管理"
					open={deptManageModalVisible}
					onCancel={() => setDeptManageModalVisible(false)}
					footer={null}
					width={800}
					destroyOnClose={true}
				>
					{deptManageModalVisible && selectedPlanId && (
						<DeptManageFormComponent
							selectedPlanId={selectedPlanId}
							onCancel={() => setDeptManageModalVisible(false)}
							onSuccess={() => {
								setDeptManageModalVisible(false);
								loadData();
							}}
						/>
					)}
				</Modal>

				{/* 附件管理模态框 */}
				<Modal
					title="附件管理"
					open={attachmentModalVisible}
					onCancel={handleCloseAttachment}
					footer={null}
					width={800}
					destroyOnClose={true}
				>
					{attachmentModalVisible && <AttachmentManagePage 
						onCancel={handleCloseAttachment} 
						planId={selectedPlanId || ''} 
					/>}
				</Modal>
			</Card>
		</Layout>
	);
};

export default RecruitmentManagementPage;